package cn.edu.pzhu.javaweb.controller;

import cn.edu.pzhu.javaweb.pojo.Userinfo;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateuserinfo")
public class UpdateUserinfoServerlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public UpdateUserinfoServerlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html"); //响应编码
        //接受参数
        String username = (String)request.getSession().getAttribute("username");//直接从域对象中获取用户名

        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        String[] types = request.getParameterValues("type");

        StringBuilder errorMsg = new StringBuilder();

        // 邮箱验证
        if (email == null || email.trim().isEmpty()) {
            errorMsg.append("邮箱不能为空");
        } else if (!email.matches("\\w+@\\w+\\.\\w+")) {
            errorMsg.append("邮箱格式不正确");
        }

        // 性别验证
        if (sex == null || !(sex.equals("0") || sex.equals("1"))) {
            errorMsg.append("性别数据错误（未获取到0或1）");
        }

        // 关注类型验证
        if (types == null || types.length == 0) {
            errorMsg.append("没有选择关注类型");
        }

        // 处理验证错误
        if (errorMsg.length() > 0) {
            request.setAttribute("error", errorMsg.toString());
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        //验证和类型转换（防御性编程）
        if(sex==null || "".equals(sex)) {
            sex="0";
        }
        Integer gender = Integer.valueOf(sex);
        String type = JSON.toJSONString(types);

        //数据封装
        Userinfo userinfo = new Userinfo(username, email, gender, type);
        //调用模型层方法来写入数据库（暂时写入server容器中）
        ServletContext application = request.getServletContext();

        application.setAttribute(username+"_userinfo", userinfo);
        response.getWriter().print("<script>alert('修改成功!');location.href='userinfo';</script>");
        return;
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
